package com.shkco.enums;

import com.shkco.exception.GlobalCustomException;
import com.shkco.exception.GlobalExceptionCode;
import com.shkco.result.JSONResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

@RestControllerAdvice
@Slf4j
public class GlobalExceptionHandler {

    @ExceptionHandler(Exception.class)
    public JSONResult exception(Exception e){
        e.printStackTrace();
        log.error("错误类型Exception,异常信息为：{}",e.getMessage());

        return JSONResult.error(GlobalExceptionCode.ERROR);
    }

    @ExceptionHandler(GlobalCustomException.class)
    public JSONResult exception(GlobalCustomException e){
        e.printStackTrace();
        log.error("错误类型GlobalCustomException,异常信息为：{}",e.getMessage());
        return JSONResult.error(e);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public JSONResult exception(MethodArgumentNotValidException e){
        e.printStackTrace();
        log.error("错误类型MethodArgumentNotValidException,异常信息为：{}",e.getMessage());
        StringBuffer sb = new StringBuffer();
        e.getBindingResult().getAllErrors().forEach(obj -> {
            sb.append(obj.getDefaultMessage()).append(";");
        });
        return JSONResult.error(sb.toString());
    }
}
